<template>
    <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <h2 class="text-center  margin-bottom">{{title}}</h2>
            <!--            @keyup.enter.native="searchQuery"-->
            <a-form layout="inline" >
                <a-row :gutter="24">
                    <!--                    <a-col :md="6" :sm="24">-->
                    <!--                        <a-form-item label="收运时间">-->
                    <!--                            <a-range-picker-->
                    <!--                                    :placeholder="['开始时间', '结束时间']"-->
                    <!--                                    v-model="rangeTime"-->
                    <!--                                    format="YYYY-MM-DD"-->
                    <!--                                    @change="handleDateChange"-->
                    <!--                            />-->
                    <!--                        </a-form-item>-->
                    <!--                    </a-col>-->
                    <a-col :md="6" :sm="24">
                        <a-form-item label="选择月份">
                            <a-month-picker placeholder="选择月份" @change="onDateChange"
                                            v-model="new Date(rangeTime[0]).Format('yyyy-MM')"/>
                        </a-form-item>
                    </a-col>

                    <!--                    <a-col :md="6" :sm="24">-->
                    <!--                        <a-form-item label="机构名称">-->
                    <!--                            <a-input v-model="queryParam.customerName" placeholder="请选择机构名称"/>-->
                    <!--                        </a-form-item>-->
                    <!--                    </a-col>-->

                    <a-col :md="8" :sm="24" v-if="customerList.length <= 0">
                        <a-form-item label="医疗机构">
                            <select-customer-list ref="selectCustomerRef" @change="changeCustomer"></select-customer-list>
                        </a-form-item>
                    </a-col>

                    <a-col :md="8" :sm="24" v-has="'query:company:select:auth'">
                        <a-form-item label="处置单位">
                            <select-company-list :companysId="queryParam.companysId" @change="changeCompany"></select-company-list>
                        </a-form-item>
                    </a-col>

                    <a-col :md="8" :sm="24" v-if="(customerList.length <= 0) && (showSelectArea)">
                        <a-form-item label="区域查询">
                            <select-area ref="selectAreaRef" @change="changeArea"></select-area>
                        </a-form-item>
                    </a-col>

                </a-row>
            </a-form>
        </div>
        <!-- 查询区域-END -->

        <!-- 操作按钮区域 -->
        <div class="table-operator" style="display: flex;justify-content: space-between;align-items: center;">
            <div>
                <a-button type="primary" @click="searchQuery" icon="search">查询数据列表</a-button>
                <a-button type="primary" @click="resetForm" v-if="customerList.length <= 0">重置查询</a-button>
            </div>
            <!--            <div v-if="selectCustomer.customerName && companyInfo.companyName">-->
            <div>
                <a-button type="primary" icon="printer" v-if="selectCustomer.customerNumber && companyInfo.companyName" v-print="'#printTableList'">打印</a-button>
                <a-button style="margin-left: 10px;" v-has="'export:electronic:face:size'" @click="handleMwExportXlsForImages" type="primary" icon="download">
                    导出电子交接联单(带手写签名)
                </a-button>
            </div>
        </div>

        <!-- table区域-begin -->
        <div>
            <CheckboxWasteType :companysId="queryParam.companysId" @change="changeWasteType"></CheckboxWasteType>
        </div>

        <div>
            <div class="ant-alert ant-alert-success countSum" >
                <div >统计：
                    <span v-for="(item,index) in wasteTypeStatistic" :key="index" v-if="item.totalWastePresentValue>0">
                        【{{item.wasteName}}： {{item.totalWastePresentValue || 0}}{{item.priceUnit || ''}} / {{item.totalWastePresentNumber || ''}}】
                    </span>
                </div>
            </div>
            <a-table
                ref="table"
                size="middle"
                bordered
                rowKey="id"
                :columns="columns"
                :dataSource="dataSource"
                :pagination="ipagination"
                :loading="loading"
                class="j-table-force-nowrap"
                @change="handleTableChange"
            >
                <template slot="htmlSlot" slot-scope="text">
                    <div v-html="text"></div>
                </template>
                <template slot="imgSlot" slot-scope="text">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                    <img v-else :src="getImgView(text)"  alt style="width: auto;height: 50px;"/>
                </template>
                <template slot="fileSlot" slot-scope="text">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
                    <a-button
                        v-else
                        :ghost="true"
                        type="primary"
                        icon="download"
                        size="small"
                        @click="uploadFile(text)"
                    >下载
                    </a-button>
                </template>
            </a-table>
        </div>

        <div v-show="false">
            <div id="printTableList" style="margin: 0 40px" >
                <h2 style="text-align: center;margin-top: 20px">
                    {{title}}
                </h2>
                <h3>医疗卫生机构名称：{{selectCustomer.customerName || '--'}}</h3>
                <h3>废物处置单位：{{companyInfo.companyName || '--'}}</h3>
                <!--                <div style="text-align: right;" v-if="rangeTime.length">-->
                <!--                    <span>时间 ： {{rangeTime[0]}} 至 {{rangeTime[1]}}</span>-->
                <!--                </div>-->
                <div style="display: flex;justify-content: space-between;">
                    <div style="color:black;">
                        <span v-for="(item,index) in wasteTypeStatistic" :key="index"
                              v-if="item.totalWastePresentValue>0">
                            【{{item.wasteName}}： {{item.totalWastePresentValue || 0}}{{item.priceUnit || ''}} / {{item.totalWastePresentNumber || ''}}】
                        </span>
                    </div>
                    <div style="text-align: right;" v-if="rangeTime.length">
                        <span>时间 ： {{new Date(rangeTime[0]).Format('yyyy年MM月')}}</span>
                    </div>
                </div>
                <a-table
                    size="default"
                    bordered
                    rowKey="id"
                    :columns="printColumns"
                    :dataSource="dataSource"
                    :pagination="false"
                    style="width: 100%;margin: 40px auto"

                >
                    <template slot="htmlSlot" slot-scope="text">
                        <div style="color: black !important;" v-html="text"></div>
                    </template>
                    <template slot="imgSlot" slot-scope="text">
                        <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                        <img v-else :src="getImgView(text)" height="25px" alt style="width: auto;height: 28px;"/>
                    </template>
                </a-table>
            </div>
        </div>

    </a-card>
</template>

<script>
/**
 * create by Jane
 * 查询各个机构电子联单数据信息
 */
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import SelectArea from '@/components/Jane/SelectArea'
import SelectCompanyList from '@/components/Jane/SelectCompanyList'
import SelectCustomerList from '@/components/Jane/SelectCustomerList'
import CheckboxWasteType from '@/components/Jane/CheckboxWasteType'

import waste from '@/api/waste'
import { downloadFile } from '@/api/manage'
import * as user from '@api/user' // 模糊下拉查询

export default {
    name: 'CxRecycleMwRecordList',
    mixins: [JeecgListMixin, mixinDevice],
    components: {
        SelectArea,
        SelectCompanyList,
        SelectCustomerList,
        CheckboxWasteType,
    },
    data() {
        return {
            title: '废物转移联单',
            selectCustomer: {
                customerNumber: null,
                customerName: null
            },
            companyInfo : {
                companyId : null,
                companyName : null,
            },

            fiveWeightAndBag: {},

            rangeTime: [],
            queryParam: {
                creatTimeBegin: null,
                creatTimeEnd: null
            },
            // 表头
            columns: [],
            printColumns: [],
            url: {
                list: null,   // 小彭接口 3.0
                exportXlsUrlOkForImages: '/hc/hcRecycleRecord/exportElectronicDuplicate'  // 小彭的接口 3.0
            },
            wasteTypeList: [], // 废物类型列表 (原始数据)
            wasteId: [],  // 选择的废物
            wasteTypeStatistic: [], // 废物分类数据统计
            customerList:[],
            // 分页参数
            ipagination: {
                pageSize: 50
            },
        }
    },

    watch:{
        statistics(newValue,oldValue){
            if(newValue && newValue){
                this.wasteTypeStatistic = newValue || [];
            }
        }
    },
    computed: {
        showSelectArea: function() {
            let state = true
            let userInfo = this.$store.getters.userInfo
            if (userInfo.provinceCode && userInfo.cityCode && userInfo.areaCode) {
                state = false
            }
            return state
        },
    },
    methods: {
        // 初始化数据
        async initData(){
            for (let i in this.queryParam) {
                this.queryParam[i] = ''
            }
            // 获取到用户登陆的信息
            let userInfo = this.$store.getters.userInfo
            // 如果用户存在区县编码、处置单位Id编号，则赋值
            if (userInfo.cityCode) {
                this.queryParam.cityCode = userInfo.cityCode
            }
            if (userInfo.areaCode) {
                this.queryParam.areaCode = userInfo.areaCode
            }
            if (userInfo.companysId) {
                this.queryParam.companysId = userInfo.companysId;
                this.companyInfo = {
                    companyId : userInfo.id,
                    companyName : userInfo.realname,
                };
            }
            this.onDateChange()
            let orgList = await user.getAllCustomerByUserId()
            if (orgList) {
                this.customerList = orgList || []
                if (orgList[0]) {
                    console.log('orgList[0].customerNumber==>', orgList[0].customerNumber)
                    this.queryParam.customerNumber = orgList[0].customerNumber
                    console.log('this.queryParam.customerNumber==>', this.queryParam.customerNumber)
                }
            }
            let ref = this.$refs.selectAreaRef
            if (ref && ref.clearSelectArea != undefined) {
                ref.clearSelectArea()
            }
            let refCus = this.$refs.selectCustomerRef;
            if(refCus && refCus.clearSelectCustomer != undefined){
                refCus.clearSelectCustomer();
            }
            // this.setColumns()
        },
        initDictConfig() {
            this.initData()
            this.setColumns()
        },

        // 数据统计查询
        // async getStatisticData() {
        //     if (this.wasteId.length) {
        //         this.queryParam.wasteId = this.wasteId.join(',')
        //     }
        //     this.queryParam.wasteId = this.wasteId.join(',')
        //     let param = { ...this.queryParam }
        //     this.wasteTypeStatistic =await waste.getWasteCountForStatistic(param)
        // },

        handleDateChange(value, dateString) {
            this.rangeTime = dateString
            if (dateString[0]) {
                this.queryParam.creatTimeBegin = dateString[0]
            }
            if (dateString[1]) {
                this.queryParam.creatTimeEnd = dateString[1]
            }
            this.searchQuery()
        },
        onDateChange(date = null) {
            var startDate = new Date().MonthFirstDay(date, 'yyyy-MM-dd hh:mm:ss')
            var endDate = new Date().MonthLastDay(date, 'yyyy-MM-dd hh:mm:ss')//:md="12" :xs="24"
            this.handleDateChange(date, [startDate, endDate])
        },
        async changeCustomer(value, label) {
            this.queryParam.customerNumber = value
            if(label != '全部'){
                this.selectCustomer = {
                    customerNumber: value,
                    customerName: label
                }
            }
            this.searchQuery()
        },
        async changeCompany(value, info,option) {
            this.queryParam.companysId = value;
            if(info){
                this.companyInfo = {
                    companyId : value,
                    companyName : info.label,
                };
            }
            await this.changeWasteType()
        },
        // 设置表格头部信息
        setColumns() {
            let data = this.wasteTypeList
            let cols = []
            data.forEach((item, index) => {
                if (item.wasteTypeName) {
                    let child = [];
                    (item['children'] || []).forEach((val, i) => {
                        let info = this.wasteId.find(v => v === val.id)
                        if (info) {
                            // 塑料输液瓶（袋）、玻璃输液瓶（袋）单位换成kg
                            if(val.id == "1366228898901467138" || val.id == "1366274806234079234"){
                                val.priceUnit = "kg"
                            }
                            child.push({
                                title: val.wasteTypeName,
                                dataIndex: 'id',
                                key: `${index}-${i}`,
                                children: [
                                    {
                                        title: '袋/箱数',
                                        align: 'center',
                                        dataIndex: 'id',
                                        key: `${index}-${i}-0`,
                                        customRender: function(vv, waste, index) {
                                            let info = (waste['list']).find((v) => v.wasteId === val.id)
                                            if (info) {
                                                return `${info.wastePresentNumber || 0}`
                                            }
                                            return ''
                                        }
                                    },
                                    {
                                        title: `废物量${val.priceUnit ? `(${val.priceUnit})` : ''}`,
                                        align: 'center',
                                        dataIndex: 'id',
                                        key: `${index}-${i}-1`,
                                        customRender: function(vv, waste, index) {
                                            let info = (waste['list']).find((v) => v.wasteId === val.id)
                                            if (info) {
                                                return `${info.wastePresentValue || 0}`
                                            }
                                            return ''
                                        }
                                    }
                                ]
                            })
                        }
                    })
                    if (child.length) {
                        let obj = {
                            title: item.wasteTypeName,
                            dataIndex: 'id',
                            key: `${index}`,
                            children: child
                        }
                        cols.push(obj)
                    }
                }
            })
            let columns = [
                ...cols,
                // {
                //     title: '收运人姓名',
                //     align: 'center',
                //     dataIndex: 'recyclePersonName'
                // },
                {
                    title: '医院交接人',
                    align: 'center',
                    dataIndex: 'customerSignatureUrl',
                    scopedSlots: { customRender: 'imgSlot' }
                },
                {
                    title: '处置单位接收人',
                    align: 'center',
                    dataIndex: 'recyclePersonUrl',
                    scopedSlots: { customRender: 'imgSlot' }
                },
                {
                    title: '废物运送车牌号',
                    align: 'center',
                    dataIndex: 'carNumber',
                    customRender: function(text) {
                        return text || ''
                    }
                }
                // {
                //     title: '备注说明',
                //     align: 'center',
                //     dataIndex: 'remarks',
                // }
            ]
            this.columns = [
                {
                    title: '序号',
                    dataIndex: '',
                    key: 'rowIndex',
                    width: 60,
                    align: 'center',
                    customRender: function(t, r, index) {
                        return parseInt(index) + 1
                    }
                },
                {
                    title: '交接时间',
                    align: 'center',
                    dataIndex: 'createTime'
                    // customRender: function(text) {
                    //     return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
                    // }
                },
                {
                    title: '医疗机构名称',
                    align: 'center',
                    dataIndex: 'customerName'
                },
                ...columns
            ]
            this.printColumns = [
                {
                    title: '序号',
                    dataIndex: '',
                    key: 'rowIndex',
                    width: 60,
                    align: 'center',
                    customRender: function(t, r, index) {
                        return parseInt(index) + 1
                    }
                },
                {
                    title: '交接时间',
                    align: 'center',
                    dataIndex: 'createTime'
                    // customRender: function(text) {
                    //     return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
                    // }
                },
                ...columns
            ]
        },

        // 废物类型选择改变
        changeWasteType(info,wasteList) {
            this.wasteId = info.ids;
            this.queryParam.wasteId = info.ids.join(',');
            this.wasteTypeList = wasteList;
            this.url.list = '/hc/hcRecycleRecord/getQueryRecycleRecordList';
            this.setColumns()
            this.loadData(1)
            // this.searchQuery()
        },



        async changeArea({ area, city }) {
            if (city) {
                this.queryParam.cityCode = city
            }
            if (area) {
                this.queryParam.areaCode = area
            }
        },


        // 重置筛选表单
        resetForm: function() {
            this.companyInfo.companyName = '';
            this.selectCustomer.customerNumber = '';
            this.initDictConfig();
            this.searchQuery();
        },

        searchQuery() {
            this.queryParam.wasteId = this.wasteId.join(',')
            this.loadData(1)
        },

        handleMwExportXlsForImages() {
            if (this.wasteId.length) {
                this.queryParam.wasteId = this.wasteId.join(',')
            } else {
                this.$message.warning('选择至少一个废物类型导出！')
                return
            }
            let param = { ...this.queryParam }

            if (!this.companyInfo.companyName) {
                this.$message.warning('请选择处置单位导出！')
                return
            }
            if (!this.selectCustomer.customerNumber) {
                this.$message.warning('请仅选择一家机构导出！')
                return
            }
            param.customerNumber = this.selectCustomer.customerNumber
            param.customerName = this.selectCustomer.customerName
            let name = `${param.customerName}电子联单-${new Date().FormatDate()}.xls`
            downloadFile(this.url.exportXlsUrlOkForImages, name, param)
        }

    }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.countSum{
    margin-bottom: 16px;
    color:#F5F5F5;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
}
   ::v-deep .ant-table-thead > tr > th, .ant-table-tbody > tr > td{
        padding: 1px !important;
    }

   ::v-deep  .ant-table-tbody .ant-table-row  td{
        padding: 0px 6px !important;

    }
   ::v-deep .ant-table table{
        width: 100% !important;
    }
   ::v-deep .ant-table-row{
       /*height: 40px !important;*/
       /*line-height: 0!important;*/
       /*display: inline-block;*/
       /*vertical-align: middle;*/
       /*width: 100%;*/
       /*line-height: 1.2;*/
       /*display: flex;*/
       /*height: 40px;*/

   }

</style>
